package Internet;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//回响客户端
//先发送请求，后接收响应
public class UdpEchoClient {
    private String severIP;//服务器IP

    private int severPort;//服务器端口号

    private DatagramSocket socket = null;

    public UdpEchoClient(String severIP, int severPort) throws SocketException {
        this.severIP = severIP;
        this.severPort = severPort;
        //客户端不能使用固定端口号,由系统随机分配
        this.socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动");

        Scanner scanner = new Scanner(System.in);

        while (true) {
            //创建请求并发送
            System.out.println("输入要发送的请求");
            if (!scanner.hasNext()) {
                break;
            }
            String request = scanner.next();

            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), 0, request.getBytes().length,
                    InetAddress.getByName(severIP), severPort);

            //发送请求
            socket.send(requestPacket);

            //接收响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //解析响应
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());

            //打印响应
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
